package config

import (
	"context"
	"fmt"
	"go-chain-api/config/setting"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
)

// MigrateDb 初始化数据库表
//func MigrateDb() error {
//	if err := global.DBEngine.AutoMigrate(&models.Blocks{}, &models.Transaction{}, &models.Events{}, &models.Topic{}, &models.Tokens{}); err != nil {
//		return err
//	}
//	return nil
//}

func NewMongodbEngine(dbConfig *setting.DbConfig) (*mongo.Client, error) {

	clientOptions := options.Client().ApplyURI("mongodb://" + dbConfig.Username + ":" + dbConfig.Pwd + "@" + dbConfig.Host + "/?authSource=" + dbConfig.DbName)

	// 连接到MongoDB
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = client.Ping(context.Background(), nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("成功连接到MongoDB")
	return client, nil
}

func NewDBEngine(dbConfig *setting.MysqlDbConfig) (*gorm.DB, error) {
	conn := "%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local"
	namingStrategy := schema.NamingStrategy{
		TablePrefix: "tian_", // 设置表前缀
	}
	fmt.Println("dbConfig:", dbConfig)
	dsn := fmt.Sprintf(conn, dbConfig.MysqlUsername, dbConfig.MysqlPwd, dbConfig.MysqlHost, dbConfig.MysqlDbName, dbConfig.MysqlCharset, dbConfig.MysqlParseTime)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: namingStrategy,
	})
	if err != nil {
		return nil, err
	}
	fmt.Println("成功连接到Mysql")
	return db, nil
}
